package com.jt;

import com.alibaba.nacos.client.utils.AppNameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class,args);
    }

    @Bean //运行时创建对象
    @LoadBalanced//这个注解描述RestTemplate对象时,系统底层对RestTemplate对象的请求进行拦截
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @RestController
    @RequestMapping("/consumer")
    public class ConsumerController{
        @Value("${spring.application.name}")
        private String appName;
        @Autowired
        private RestTemplate restTemplate;
        @Autowired
        private RestTemplate loadBalancerrestTemplate;

        /*负载均衡客户端对象(基于此对象可以从nacos中获取服务列表,并且基于一定的算法)*/
        //从列表中获取一个服务实例
        @Autowired
        private LoadBalancerClient loadBalancerClient;

        /*RestTemplate对象进行远程服务的访问①*/
        @GetMapping("/echo1")
        public String doEcho1(){
            String url = "http://localhost:8081/provider/echo/"+ appName;
            System.out.println("请求的路径"+url);

            return restTemplate.getForObject(url,String.class);
        }

        /*负载均衡方式的调用①*/
        @GetMapping("/echo2")
        public String doEcho2(){
            //基于LoadBalancerClient方式获取服务实例
            //String serviceId = "provider";
            ServiceInstance choose = loadBalancerClient.choose("provider");
            String ip = choose.getHost();
            int port = choose.getPort();
            String url = String.format("http://%s:%s/provider/echo/%s",ip,port,appName);
            return restTemplate.getForObject(url,String.class);
        }


        /*负载均衡应用的方式②: @LoadBalanced*/
        @GetMapping("/echo3")
        public String doEcho3(){
            String serviceId = "provider";
            String url = String.format("http://%s:%s/provider/echo/%s",serviceId,appName);
            //底层在基于loadBalancerrestTemplate对象访问方式,会启动一个拦截器进行拦截
            return loadBalancerrestTemplate.getForObject(url,String.class);
        }
    }


}
